package com.amigo.online.provider.user.service.impl;

import java.time.Instant;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.amigo.online.common.param.dto.user.RecordDeviceDto;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.provider.user.common.GlobalController;
import com.amigo.online.provider.user.mapper.RecordDeviceMapper;
import com.amigo.online.provider.user.model.entity.UserDevice;
import com.amigo.online.provider.user.service.RecordDeviceService;

@Service
public class RecordDeviceServiceImpl implements RecordDeviceService {

    @Autowired
    private RecordDeviceMapper recordDeviceMapper;

    @Override
    public boolean insert(RecordDeviceDto dto) {
        UserInfo localUser = GlobalController.getNowUser();
        UserDevice rs = recordDeviceMapper.getByUserId(localUser.getId());
        // 这个userId第一次登陆，数据库中没有记录
        if (rs == null) {
            UserDevice userDevice = new UserDevice();
            userDevice.setUserId(localUser.getId());
            userDevice.setType(dto.getType());
            userDevice.setUniqueCode(dto.getUniqueCode());
            userDevice.setCreatedTime(Instant.now().getEpochSecond());
            recordDeviceMapper.insertSelective(userDevice);
            return true;
        }
        // 这个userId登陆过，但是已经退出了登陆，或者UniqueCode改变了，只需要更新UniqueCode和UpdatedTime
        if (!StringUtils.equals(dto.getUniqueCode(), rs.getUniqueCode())) {
            UserDevice userDevice = new UserDevice();
            userDevice.setId(rs.getId());
            userDevice.setUniqueCode(dto.getUniqueCode());
            userDevice.setUpdatedTime(Instant.now().getEpochSecond());
            recordDeviceMapper.updateByPrimaryKeySelective(userDevice);
        }
        return true;
    }

}
